package com.example.administrator.baikangxing.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.util.ArraySet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;


import com.example.administrator.baikangxing.MediaManager;
import com.example.administrator.baikangxing.R;
import com.example.administrator.baikangxing.bean.BindDevice;
import com.example.administrator.baikangxing.bean.Recorder;
import com.example.administrator.baikangxing.VoiceListAdapter;
import com.example.administrator.baikangxing.config.Constants;
import com.example.administrator.baikangxing.config.Url;
import com.example.administrator.baikangxing.utils.Base64Utils;
import com.example.administrator.baikangxing.utils.HttpUtil;
import com.example.administrator.baikangxing.utils.LogUtil;
import com.example.administrator.baikangxing.utils.ToastUtil;
import com.example.administrator.baikangxing.view.AudioRecordButton;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class VoiceActivity extends BaseActivity {
    private AudioRecordButton btnRecord;
    private ListView voiceList;
    private ArrayAdapter<Recorder> mAdapter;
    private List<Recorder> mDatas = new ArrayList<Recorder>();

    private AnimationDrawable animation;
    private View voiceAnim;
    private String select_dev_id;
    private int voice_length;

    @Override
    public int getContentViewLayoutId() {
        return R.layout.activity_voice;
    }

    @Override
    public void initView() {
        Intent intent = getIntent();
        BindDevice chat_dev = (BindDevice) intent.getSerializableExtra(Constants.CHAT_DEVID);
        select_dev_id = chat_dev.getDevid();
        setTitles(chat_dev.getNickname());
        Set<String> tags = new ArraySet<>();
        tags.add("人");
        JPushInterface.setAliasAndTags(this, "123", tags, new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
                if(i == 0){
                    Toast.makeText(VoiceActivity.this, "设置成功", Toast.LENGTH_SHORT).show();
                    LogUtil.e("设置别名成功");
                }
            }
        });
        voiceList = (ListView) findViewById(R.id.voiceList);
        btnRecord = (AudioRecordButton) findViewById(R.id.btnRecord);
        btnRecord
                .setAudioRecordFinishListener(new MyAudioRecordFinishListener());

        mAdapter = new VoiceListAdapter(this, mDatas);
        voiceList.setAdapter(mAdapter);
        voiceList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (animation != null) {
                    voiceAnim
                            .setBackgroundResource(R.drawable.icon_voice_ripple);
                    voiceAnim = null;
                }
                voiceAnim = view.findViewById(R.id.voiceAnim);
                voiceAnim.setBackgroundResource(R.drawable.anim_play_audio);
                animation = (AnimationDrawable) voiceAnim.getBackground();
                animation.start();
                MediaManager.playSound(mDatas.get(position).getFilePath(),
                        new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                voiceAnim
                                        .setBackgroundResource(R.drawable.icon_voice_ripple);
                            }
                        });

            }
        });
    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {

    }

    class MyAudioRecordFinishListener implements AudioRecordButton.AudioRecordFinishListener {

        @Override
        public void onFinish(float second, String filePath) {
            // TODO Auto-generated method stub
            Recorder recorder = new Recorder(second, filePath,new Date(), Recorder.Type.outVoice);
            mDatas.add(recorder);
            mAdapter.notifyDataSetChanged();
            voiceList.setSelection(mDatas.size() - 1);
            String base64_voice = doFileUpload(filePath);
            String[] values = new String[]{select_dev_id, "ext", String.valueOf(voice_length), base64_voice};
            LogUtil.e("发送的人是："+select_dev_id);
            HttpUtil.getInstance().postString(Url.send_voice, new String[]{"devid", "ext", "len", "voice"}, values, new HttpUtil.CallBackPostString() {
                @Override
                public void onSuccess(JSONObject successString) {
                    try {
                        if(successString.getString("errorCode").equals("0")){
                            ToastUtil.showToast("发送成功");
                            LogUtil.e("语音发送成功");
                        }else {
                            ToastUtil.showToast("发送失败"+successString.getString("errorInfo"));
                            LogUtil.e("发送失败的原因："+successString.getString("errorCode")+successString.getString("errorInfo"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFail(JSONObject failString) {

                }

                @Override
                public void onProgress(long bytesWritten, long totalSize) {

                }
            });
        }

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        MediaManager.release();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MediaManager.pause();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MediaManager.resume();
    }

    private String doFileUpload(String selectedPath){
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            FileInputStream fis = new FileInputStream(new File(selectedPath));

            byte[] buf = new byte[1024];
            int n;
            while (-1 != (n = fis.read(buf))){
                baos.write(buf, 0, n);
            }
            byte[] bytes = baos.toByteArray();
            voice_length = bytes.length;
            LogUtil.e("直接获取到的大小为："+voice_length);
            String s = new String(bytes);
            String base64 = Base64Utils.getBase64(s);
            LogUtil.e("发送的音频base64："+base64);
            return base64;
        } catch (Exception e) {
            // TODO: handle exception
            return null;
        }

    }

}
